<template>
	<view class="payment-container page-container">
		<!-- 配送方式 -->
		<view class="delivery-section">
			<view class="section-title">
				<text class="title-text">配送方式</text>
			</view>
			<view class="delivery-options">
				<view class="delivery-item" :class="{ active: receive_type === 1 }" @click="selectDeliveryType(1)">
					<view class="delivery-info">
						<text class="delivery-name">快递配送</text>
						<text class="delivery-desc">48小时内发货</text>
					</view>
					<view class="delivery-radio">
						<view class="radio" :class="{ checked: receive_type === 1 }"></view>
					</view>
				</view>
				<view class="delivery-item" :class="{ active: receive_type === 2 }" @click="selectDeliveryType(2)">
					<view class="delivery-info">
						<text class="delivery-name">上门自提</text>
						<text class="delivery-desc">到店即可取货</text>
					</view>
					<view class="delivery-radio">
						<view class="radio" :class="{ checked: receive_type === 2 }"></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 收货地址 -->
		<view class="address-section" v-if="receive_type === 1">
			<view class="section-header">
				<text class="title-text">收货地址</text>
				<button class="add-address-btn" @click="selectAddress">
					+ 选择地址
				</button>
			</view>
			<view v-if="defaultAddress && defaultAddress.id>0" class="address-list">
				<view class="address-item active">
					<view class="address-content">
						<view class="address-header">
							<text class="recipient-name">{{ defaultAddress.realname }}</text>
							<text class="recipient-phone">{{ defaultAddress.mobile }}</text>
							<text class="default-tag" v-if="defaultAddress.tag_name === 'home'">家</text>
							<text class="default-tag" v-else-if="defaultAddress.tag_name === 'company'">公司</text>
							<text class="default-tag" v-else-if="defaultAddress.tag_name === 'school'">学校</text>
							<text class="default-tag" v-else-if="defaultAddress.tag_name === 'other'">其他</text>
						</view>
						<text class="address-detail">
							{{ defaultAddress.province.name }} {{ defaultAddress.city.name }}
							{{ defaultAddress.town.name }} {{ defaultAddress.address }}
						</text>
					</view>
					<view class="address-radio">
						<view class="radio checked"></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 商品信息 -->
		<view class="product-section">
			<view class="section-title">
				<text class="title-text">商品信息</text>
			</view>
			<view class="product-list">
				<view class="product-item" v-for="(item, index) in orderProducts" :key="index">
					<image :src="$tools.buildUrl(item.main_image)" mode="aspectFill" class="product-image"></image>
					<view class="product-info">
						<text class="product-name">{{ item.spu_name }}</text>
						<text class="product-spec">{{ item.sku_name }}</text>
						<view v-if="[1,3].includes(item.exchange_type)" class="product-bottom">
							<text class="product-price">{{ item.exchange_points }} 积分</text>
							<text class="product-quantity">x{{ item.quantity }}</text>
						</view>
						<view v-if="[2,3].includes(item.exchange_type)" class="exchange-methods">
							<view class="cards-requirement">
								<text v-for="(card, cardindex) in item.exchange_cards" :key="cardindex" class="card-req"
									:class="card.level">
									{{ card.count }}{{ card.level }}
								</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 支付方式 -->
		<view class="payment-methods">
			<view class="section-title">
				<text class="title-text">兑换方式</text>
			</view>
			<view class="method-list">
				<block v-for="(method, index) in paymentMethods" :key="index">
					<view class="method-item" v-if="method.disabled" :class="{ active: selectedMethod === method.id }"
						@click="selectMethod(method.id)">
						<view class="method-left">
							<u-icon :name="method.icon" size="24"
								:color="selectedMethod === method.id ? '#52a58a' : '#666'"></u-icon>
							<view class="method-info">
								<text class="method-name">{{ method.name }}</text>
								<text class="method-desc">{{ method.desc }}</text>
							</view>
						</view>
						<view class="method-right">
							<u-icon name="checkmark-circle-fill" size="20"
								:color="selectedMethod === method.id ? '#52a58a' : '#e5e5e5'"></u-icon>
						</view>
					</view>
				</block>
			</view>
		</view>

		<!-- 优惠券(兑换商品不享受优惠券) -->
		<!-- <view v-if="paymentInfo.orderCoupon>0" class="coupon-section">
			<view class="coupon-left">
				<u-icon name="coupon" size="20" color="#ff4757"></u-icon>
				<text class="coupon-text">已优惠</text>
			</view>
			<view class="coupon-right">
				<text class="coupon-selected">-¥{{ paymentInfo.orderCoupon }}</text>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
		</view>
		<view v-else-if="(couponList && couponList.length>0) || selectedCoupon.id>0" class="coupon-section"
			@click="selectCoupon">
			<view class="coupon-left">
				<u-icon name="coupon" size="20" color="#ff4757"></u-icon>
				<text class="coupon-text">{{couponList.length}} 张优惠券</text>
			</view>
			<view class="coupon-right">
				<text class="coupon-selected" v-if="selectedCoupon.id">-¥{{ selectedCoupon.couponAmount }}</text>
				<text class="coupon-placeholder" v-else>选择优惠券</text>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
		</view> -->

		<!-- 费用明细 -->
		<view class="cost-section">
			<view class="section-title">
				<text class="title-text">费用明细</text>
			</view>
			<view v-if="selectedMethod===1 && paymentInfo.goodPoints>0" class="cost-item">
				<text class="cost-label">商品积分</text>
				<text class="cost-value">{{ paymentInfo.goodPoints }} 积分</text>
			</view>
			<view v-if="selectedMethod===2 && paymentInfo.goodCards.length>0" class="cost-item">
				<text class="cost-label">商品积分卡</text>
				<view class="exchange-methods">
					<view class="method-item">
						<view class="cards-requirement" style="margin-left: auto;">
							<text v-for="(card, cardindex) in paymentInfo.goodCards" :key="cardindex" class="card-req"
								:class="card.level">
								{{ card.count }}{{ card.level }}
							</text>
						</view>
					</view>
				</view>
			</view>
			<!-- <view class="cost-item">
				<text class="cost-label">运费金额</text>
				<text class="cost-value">¥ {{ shippingFee }}</text>
			</view> -->
			<!-- <view class="cost-item" v-if="selectedCoupon.id">
				<text class="cost-label">优惠金额</text>
				<text class="cost-value discount">- ¥ {{ selectedCoupon.couponAmount }}</text>
			</view> -->
			<view v-if="selectedMethod===1" class="cost-item total">
				<text class="cost-label">实付积分</text>
				<text class="cost-value">{{ finalPoints }} 积分</text>
			</view>
			<view v-else-if="selectedMethod===2" class="cost-item total">
				<text class="cost-label">实付积分卡</text>
				<view class="exchange-methods">
					<view class="method-item">
						<view class="cards-requirement" style="margin-left: auto;">
							<text v-for="(card, cardindex) in finalCards" :key="cardindex" class="card-req"
								:class="card.level">
								{{ card.count }}{{ card.level }}
							</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 买家备注 -->
		<view class="cost-section">
			<view class="section-title">
				<text class="title-text">买家留言</text>
			</view>
			<view class="form-item">
				<textarea class="form-textarea" placeholder="请输入备注内容" v-model="buyer_words" maxlength="200"></textarea>
			</view>
		</view>

		<!-- 底部支付按钮 -->
		<view class="payment-footer fixed-bottom-safe">
			<view v-if="selectedMethod===1" class="payment-info">
				<text class="total-label">合计：</text>
				<text class="total-amount">{{ finalPoints }} 积分</text>
			</view>
			<view v-else-if="selectedMethod===2" class="payment-info">
				<text class="total-label">合计：</text>
				<view class="exchange-methods">
					<view class="method-item">
						<view class="cards-requirement">
							<text v-for="(card, cardindex) in finalCards" :key="cardindex" class="card-req"
								:class="card.level">
								{{ card.count }}{{ card.level }}
							</text>
						</view>
					</view>
				</view>
			</view>
			<button class="pay-btn" @click="submitOrder" :disabled="!canPay">
				{{ limitDelivery?'地区限售':'立即兑换' }}
			</button>
		</view>

		<!-- 支付密码弹窗 -->
		<u-popup :show="passwordPopupShow" mode="center" border-radius="20" @close="passwordPopupShow = false">
			<view class="password-popup">
				<view class="popup-header">
					<text class="popup-title">输入支付密码</text>
					<u-icon name="close" size="20" color="#999" @click="passwordPopupShow = false"></u-icon>
				</view>
				<view class="popup-content">
					<text v-if="selectedMethod===1" class="popup-amount">{{ finalPoints }} 积分</text>
					<view v-else-if="selectedMethod===2" class="exchange-methods">
						<view class="method-item">
							<view class="cards-requirement">
								<text v-for="(card, cardindex) in finalCards" :key="cardindex" class="card-req"
									:class="card.level">
									{{ card.count }}{{ card.level }}
								</text>
							</view>
						</view>
					</view>
					<view class="password-input">
						<view class="password-dot" v-for="n in 6" :key="n"
							:class="{ filled: n < paymentPassword.length }"></view>
					</view>
				</view>
				<view class="number-keyboard">
					<view class="keyboard-row" v-for="(row, rowIndex) in keyboard" :key="rowIndex">
						<view class="keyboard-key" v-for="(key, keyIndex) in row" :key="keyIndex"
							@click="inputPassword(key)">
							<text class="key-text" v-if="key !== 'delete'">{{ key }}</text>
							<u-icon name="backspace" size="20" color="#333" v-else></u-icon>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				shop_id: '',
				store_id: '',
				spu_id: '',
				sku_id: '',
				quantity: 1,
				pay_order_id: '', // 创建支付订单ID
				receive_type: 1, // 收件方式：1-邮寄，2-自提
				limitDelivery: false, // 是否限售地区
				freeDelivery: false, // 是否免邮
				orderProducts: [], // 订单商品明细
				userExtInfo: {
					points: 0, // 当前拥有积分
					cardsList: [], // 当前拥有积分卡
				},
				shippingFee: 0, // 运费金额
				freightTemplates: [], // 运费模板（多个）
				defaultAddress: {}, // 收货地址
				selectedMethod: 1, // 支付方式
				selectedCoupon: {}, // 选择优惠券
				couponList: [], // 可用优惠券
				buyer_words: '', // 买家留言
				passwordPopupShow: false, // 支付密码弹框
				paymentPassword: '', // 支付密码
				paymentInfo: {
					goodPoints: 0, // 商品总积分
					goodCards: [], // 商品积分卡
					orderCoupon: 0, // 订单优惠
					totalWeight: 0, // 总重量
					totalVolume: 0, // 总体积
					totalQuantity: 0, // 总数量
					desc: '六堡茶经典装'
				},
				// 兑换类型：1-积分 2-积分卡
				paymentMethods: [{
						id: 1,
						name: '积分支付',
						desc: '我的积分：0.00',
						icon: 'gift-fill',
						disabled: true
					},
					{
						id: 2,
						name: '积分卡支付',
						desc: '我的积分卡：',
						icon: 'red-packet-fill',
						disabled: true
					}
				],
				keyboard: [
					['1', '2', '3'],
					['4', '5', '6'],
					['7', '8', '9'],
					['', '0', 'delete']
				]
			}
		},
		watch: {
			shippingFeeFlag(newValue, oldValue) {
				if (newValue !== oldValue) {
					if (this.receive_type === 1 && this.defaultAddress.id > 0) {
						this.calculateFreight();
					}
				}
			}
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo', 'dealerInfo', 'openid']),

			// 运费
			shippingFeeFlag() {
				const addrid = this.defaultAddress.id > 0 ? this.defaultAddress.id : 0;
				let flag = this.receive_type + addrid + this.paymentInfo.totalWeight + this.paymentInfo
					.totalVolume + this.paymentInfo.totalQuantity;
				return flag
			},
			// 实付积分
			finalPoints() {
				return this.paymentInfo.goodPoints
			},
			// 实付积分卡
			finalCards() {
				return this.paymentInfo.goodCards
			},
			// 是否可以兑换
			canPay() {
				if (this.receive_type === 1) {
					return this.defaultAddress.id > 0 && this.canExchange()
				} else {
					// 自提模式
					return this.canExchange();
				}
			}
		},
		onLoad(options) {
			// 初始化订单数据
			if (options.receive_type) {
				this.receive_type = Number(options.receive_type)
			}
			if (options.spu_id) {
				this.spu_id = options.spu_id
			}
			if (options.sku_id) {
				this.sku_id = options.sku_id
			}
			if (options.quantity) {
				this.quantity = options.quantity
			}
			this.loadOrderData();
			// this.loadCouponValid();
			this.userDefaultAddress();
		},
		onShow() {
			this.loadPointInfo();
		},
		methods: {
			// 初始化订单数据
			loadOrderData() {
				if (this.sku_id && Number(this.sku_id) > 0) {
					this.$api.good.GetProductSkuInfo({
						sku_id: this.sku_id
					}).then(res => {
						const exchange_points = parseFloat(res.data.exchange_points);
						const exchange_cards = this.$tools.parseJsonObject(res.data.exchange_cards);
						let total_cards = [...exchange_cards]
						total_cards.forEach(item => {
							item.count = item.count * this.quantity;
						})
						const skuData = {
							spu_id: res.data.spu_id,
							sku_id: res.data.id,
							shop_id: res.data.shop_id,
							store_id: res.data.store_id,
							platform_type: res.data.platform_type,
							spu_name: res.data.spu_name,
							sku_name: res.data.sku_name,
							package_sku: res.data.package_sku,
							main_image: res.data.white_back_ground_pic_url,
							quantity: this.quantity,
							exchange_type: res.data.exchange_type,
							exchange_points: exchange_points,
							exchange_cards: exchange_cards,
							total_points: exchange_points * this.quantity,
							total_cards: total_cards,
							stock_num: res.data.stock_num,
							available_stock: res.data.available_stock,
							locked_stock: res.data.locked_stock,
							sold_stock: res.data.sold_stock,
							weight: res.data.weight,
							volume: res.data.volume,
							coupon_id: res.data.coupon_id,
							coupon_amount: res.data.coupon_amount,
							warehouse_id: res.data.warehouse_id,
							warehouse_name: res.data.warehouse_name,
							warehouse_sku_id: res.data.warehouse_sku_id,
							warehouse_sku_name: res.data.warehouse_sku_name,
							baocai_id: res.data.baocai_id,
							baocai_name: res.data.baocai_name,
							baocai_cost: res.data.baocai_cost,
							cost_price: res.data.cost_price,
							purchase_price: res.data.purchase_price,
							unit_price: res.data.unit_price || 0,
							total_amount: (res.data.unit_price || 0) * this.quantity,
							weight: res.data.weight,
							volume: res.data.volume,
							l: res.data.l,
							w: res.data.w,
							h: res.data.h,
							reduce_type: res.data.reduce_type
						};
						this.shop_id = skuData.shop_id;
						this.store_id = skuData.store_id;
						this.orderProducts = [skuData];
						if (skuData.exchange_type !== 3) {
							this.selectedMethod = skuData.exchange_type;
						}
						this.paymentMethods.forEach(item => {
							if (item.id === skuData.exchange_type || skuData.exchange_type === 3) {
								item.disabled = true
							} else {
								item.disabled = false
							}
						})
						this.paymentInfo = {
							goodPoints: skuData.total_points,
							goodCards: skuData.total_cards,
							totalWeight: parseFloat(skuData.weight) * this.quantity,
							totalVolume: parseFloat(skuData.volume) * this.quantity,
							totalQuantity: this.quantity,
							desc: skuData.spu_name
						}
						this.freightTemplates = [res.data.freight_template]; // 单个运费模板
					})
				}
			},
			loadPointInfo() {
				// 加载用户积分信息
				this.$api.user.GetUserExtInfo2().then(res => {
					// console.log('加载用户积分信息', res.data)
					if (res.data && res.data.points) {
						this.userExtInfo.points = parseFloat(res.data.points)
						this.paymentMethods[0].desc = '我的积分：' + this.userExtInfo.points;
					}
					if (res.data && res.data.cardsList) {
						this.userExtInfo.cardsList = this.$tools.parseJsonObject(res.data.cardsList)
						console.log(this.userExtInfo.cardsList)
						this.paymentMethods[1].desc = '我的积分卡：'
						this.userExtInfo.cardsList.forEach(item => {
							this.paymentMethods[1].desc += item.sy_points + item.scorecard + ' ';
						})
					}
				})
			},
			// 检查是否可以兑换   兑换方式：1-积分 2积分卡 3两者均可
			canExchange() {
				if (this.selectedMethod === 1) {
					return this.userExtInfo.points >= this.finalPoints
				} else if (this.selectedMethod === 2) {
					return this.canExchangeWithCards(this.finalCards)
				} else if (this.selectedMethod === 3) {
					return this.userExtInfo.points >= this.finalPoints || this.canExchangeWithCards(this.finalCards)
				}
				return false
			},
			// 检查积分卡是否足够
			canExchangeWithCards(cardsRequired) {
				if (!cardsRequired) return false
				if (!(this.userExtInfo.cardsList && this.userExtInfo.cardsList.length > 0)) return false
				for (let index in cardsRequired) {
					const ii = this.userExtInfo.cardsList.findIndex(item => item.scorecard === cardsRequired[index]
						.level && item.sy_points >= cardsRequired[index].count);
					if (ii < 0) {
						return false;
					}
				}
				return true
			},
			loadCouponValid() {
				// 加载优惠券信息
				this.$api.user.GetCouponValid().then(res => {
					this.couponList = res.data
				})
			},
			userDefaultAddress() {
				// 用户默认收货地址
				this.$api.user.GetDefaultAddress().then(res => {
					this.defaultAddress = res.data
					this.defaultAddress.mobile = this.$secret.decryptAES(this.defaultAddress.mobile)
					this.defaultAddress.address = this.$secret.decryptAES(this.defaultAddress.address)
					this.defaultAddress.province = this.$tools.parseJsonObject(this.defaultAddress.province)
					this.defaultAddress.city = this.$tools.parseJsonObject(this.defaultAddress.city)
					this.defaultAddress.town = this.$tools.parseJsonObject(this.defaultAddress.town)
					this.defaultAddress.street = this.$tools.parseJsonObject(this.defaultAddress.street)
				})
			},
			calculateFreight() {
				// 根据运费模板和收货地址计算运费 
				if (!(this.defaultAddress && this.defaultAddress.id > 0)) {
					return;
				}
				if (!(this.freightTemplates && this.freightTemplates.length > 0)) {
					return;
				}
				this.shippingFee = 0;
				const province = this.defaultAddress.province
				const city = this.defaultAddress.city
				const town = this.defaultAddress.town
				for (var i = 0; i < this.freightTemplates.length; i++) {
					// 计价方式：1-按重量 2-按件数 3-按体积
					const calculate_type = this.freightTemplates[i].calculate_type
					// 运费类型-0:阶梯计价 1:固定运费 2:卖家包邮 3:货到付款
					const freight_rule_type = this.freightTemplates[i].rule_type
					// 规则类型（1:默认运费；2:指定地区运费；3:指定条件包邮；4:指定限售地区）
					let ruleArray = this.freightTemplates[i].ruleArray
					ruleArray.forEach(item => {
						item.rule_address = this.$tools.parseJsonObject(item.rule_address)
						item.rule_address.forEach(pcs => {
							const ii = item.rule_address.findIndex(o => o.code !== pcs.code && o.code
								.startsWith(pcs.code));
							if (ii >= 0) {
								pcs.hasChildren = true;
							} else {
								pcs.hasChildren = false;
							}
						});
						const new_rule_address = item.rule_address.filter(pcs => !pcs.hasChildren);
						item.rule_address = new_rule_address; // 只保留末级节点
					})

					// step1. 限售地区 [{ "code": "32", "name": "江苏省" }]
					this.limitDelivery = false;
					const limitArea = ruleArray.filter(item => item.rule_type === 4)
					if (limitArea && limitArea.length > 0) {
						limitArea.forEach(item => {
							const index1 = item.rule_address.findIndex(node => node.code === province.code || node
								.name === province.name);
							const index2 = item.rule_address.findIndex(node => node.code === city.code || node
								.name ===
								city.name);
							const index3 = item.rule_address.findIndex(node => node.code === town.code || node
								.name ===
								town.name);
							if (index1 >= 0 || index2 >= 0 || index3 >= 0) {
								this.limitDelivery = true;
							}
						})
					}
					if (this.limitDelivery) {
						this.shippingFee = 0;
						return;
					}
					// step2. 卖家包邮 或 货到付款
					if (freight_rule_type >= 2) {
						this.freeDelivery = true;
						this.shippingFee = 0;
						return;
					}
					// step3. 指定条件包邮
					this.freeDelivery = false;
					const baoyouArea = ruleArray.filter(item => item.rule_type === 3)
					if (baoyouArea && baoyouArea.length > 0) {
						baoyouArea.forEach(item => {
							const index1 = item.rule_address.findIndex(node => node.code === province.code || node
								.name === province.name);
							const index2 = item.rule_address.findIndex(node => node.code === city.code || node
								.name ===
								city.name);
							const index3 = item.rule_address.findIndex(node => node.code === town.code || node
								.name ===
								town.name);
							if (index1 >= 0 || index2 >= 0 || index3 >= 0) {
								// 满xx包邮 计量单位（1-元 2-kg 3-cm³）
								if (item.over_danwei === 1 && this.paymentInfo.goodAmount >= item.over_number) {
									this.freeDelivery = true;
								} else if (item.over_danwei === 2 && this.paymentInfo.totalWeight >= item
									.over_number) {
									this.freeDelivery = true;
								} else if (item.over_danwei === 2 && this.paymentInfo.totalVolume >= item
									.over_number) {
									this.freeDelivery = true;
								}
							}
						})
					}
					if (this.freeDelivery) {
						this.shippingFee = 0;
						return;
					}
					// step4. 指定地区计算邮费（取最高）
					let isCharging = false;
					let maxChargingFreight = 0;
					const chargingArea = ruleArray.filter(item => item.rule_type === 2)
					if (chargingArea && chargingArea.length > 0) {
						chargingArea.forEach(item => {
							const index1 = item.rule_address.findIndex(node => node.code === province.code || node
								.name === province.name);
							const index2 = item.rule_address.findIndex(node => node.code === city.code || node
								.name ===
								city.name);
							const index3 = item.rule_address.findIndex(node => node.code === town.code || node
								.name ===
								town.name);
							if (index1 >= 0 || index2 >= 0 || index3 >= 0) {
								isCharging = true;
								// 阶梯计费 或 固定运费 calculate_type 计价方式：1-按重量 2-按件数 3-按体积
								let basicValue = 0;
								let thisChargingFreight = 0;
								if (calculate_type === 1) {
									basicValue = this.paymentInfo.totalWeight;
								} else if (calculate_type === 2) {
									basicValue = this.paymentInfo.totalQuantity;
								} else {
									basicValue = this.paymentInfo.totalVolume;
								}
								if (freight_rule_type === 0) {
									thisChargingFreight = item.first_price;
									basicValue -= parseFloat(item.first_unit);
									if (basicValue > 0 && parseFloat(item.add_unit) > 0) {
										// 向上取整
										thisChargingFreight += Math.ceil(basicValue / parseFloat(item.add_unit)) *
											parseFloat(item.add_price);
									}
								} else if (freight_rule_type === 1) {
									thisChargingFreight = item.fixed_amount;
								}

								if (thisChargingFreight > maxChargingFreight) {
									maxChargingFreight = thisChargingFreight;
								}
							}
						})
					}
					if (isCharging) {
						if (maxChargingFreight > this.shippingFee) {
							this.shippingFee = maxChargingFreight;
						}
						continue;
					}

					// step5. 默认运费规则（取最高）
					let maxDefaultFreight = 0;
					const defaultArea = ruleArray.filter(item => item.rule_type === 1)
					if (defaultArea && defaultArea.length > 0) {
						defaultArea.forEach(item => {
							// 阶梯计费 或 固定运费 calculate_type 计价方式：1-按重量 2-按件数 3-按体积
							let basicValue = 0;
							let thisDefaultFreight = 0;
							if (calculate_type === 1) {
								basicValue = this.paymentInfo.totalWeight;
							} else if (calculate_type === 2) {
								basicValue = this.paymentInfo.totalQuantity;
							} else {
								basicValue = this.paymentInfo.totalVolume;
							}
							if (freight_rule_type === 0) {
								thisDefaultFreight = item.first_price;
								basicValue -= parseFloat(item.first_unit);
								if (basicValue > 0 && parseFloat(item.add_unit) > 0) {
									// 向上取整
									thisDefaultFreight += Math.ceil(basicValue / parseFloat(item.add_unit)) *
										parseFloat(item.add_price);
								}
							} else if (freight_rule_type === 1) {
								thisDefaultFreight = item.fixed_amount;
							}

							if (thisDefaultFreight > maxDefaultFreight) {
								maxDefaultFreight = thisDefaultFreight;
							}
						})
					}
					if (maxDefaultFreight > this.shippingFee) {
						this.shippingFee = maxDefaultFreight;
					}
				}
			},
			// 选择配送方式
			selectDeliveryType(type) {
				this.receive_type = type
			},
			// 选择收货地址
			selectAddress() {
				uni.navigateTo({
					url: '/pages/user/address?type=select'
				})
			},
			// 选择收货地址结果
			selectAddressEvent(address) {
				this.defaultAddress = address
			},

			// 选择优惠券
			selectCoupon() {
				uni.navigateTo({
					url: '/pages/user/coupon?type=select'
				})
			},
			// 选择优惠券结果
			selectCouponEvent(item) {
				this.selectedCoupon = item
				// 优惠内容（1:满减券 2:直减券 3:折扣券）
				let couponAmount = 0;
				if (item.content_type === 3) {
					couponAmount = parseFloat(this.paymentInfo.goodAmount) * parseFloat(item.discount) / 100;
				} else if (item.content_type === 2) {
					couponAmount = item.coupon_amount;
				} else if (item.content_type === 1) {
					if (parseFloat(this.paymentInfo.goodAmount) > parseFloat(item.threshold)) {
						couponAmount = item.coupon_amount;
					}
				}
				this.selectedCoupon.couponAmount = couponAmount;
			},

			// 选择支付方式
			selectMethod(methodId) {
				this.selectedMethod = methodId
			},

			// 提交订单
			submitOrder() {
				if (this.receive_type === 1 && !(this.defaultAddress.id > 0)) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
					return
				}

				if (!(this.selectedMethod > 0)) {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none'
					})
					return
				}

				// 是否设置了支付密码
				if (this.userInfo.has_password_secure !== '已设置') {
					uni.showModal({
						title: '支付密码',
						content: '您尚未设置支付密码，是否立即设置？',
						success: (res) => {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/user/pay-password'
								})
							}
						}
					})
					return
				}

				if (this.pay_order_id > 0) {
					this.submitPayment();
					return;
				}

				// 构建订单数据
				const orderData = {
					shop_id: this.shop_id,
					store_id: this.store_id,
					spu_id: this.spu_id,
					sku_id: this.sku_id,
					quantity: this.quantity,
					cart_ids: this.cart_ids,
					order_ids: this.order_ids,
					receive_type: this.receive_type, // 收件方式：1-邮寄，2-自提					
					addressInfo: this.receive_type === 1 ? this.defaultAddress : '', // 收货地址
					exchange_type: this.selectedMethod, // 支付方式 1-积分 2-积分卡
					couponInfo: this.selectedCoupon, // 优惠券
					buyer_words: this.buyer_words, // 买家留言
					paymentPassword: this.$secret.encryptAES(this.paymentPassword), // 支付密码(加密)
					goodPoints: this.paymentInfo.goodPoints, // 商品积分
					orderAmount: this.paymentInfo.goodCards, // 商品积分卡	
					finalPoints: this.finalPoints, // 实付积分
					finalCards: this.finalCards, // 实付积分卡
					shippingFee: this.shippingFee, // 运费金额
					couponAmount: this.selectedCoupon.couponAmount, // 优惠金额	
					totalWeight: this.paymentInfo.totalWeight, // 总重量
					totalVolume: this.paymentInfo.totalVolume, // 总体积
					totalQuantity: this.paymentInfo.totalQuantity, // 总数量	
					orderProducts: this.orderProducts, // 订单商品明细
					openid: this.openid
				}

				uni.showLoading({
					title: '正在提交订单...'
				})

				// 保存订单信息
				this.$api.point.AddPointOrders(orderData).then(res => {
					uni.hideLoading();
					// 输出订单支付信息
					this.pay_order_id = res.data;
					this.submitPayment();
				})
			},

			// 提交支付
			submitPayment() {
				if (!this.canPay) return

				// 如果是余额支付，需要输入密码
				this.passwordPopupShow = true
			},

			// 输入支付密码
			inputPassword(key) {
				if (key === 'delete') {
					this.paymentPassword = this.paymentPassword.slice(0, -1)
				} else if (key && this.paymentPassword.length < 6) {
					this.paymentPassword += key

					// 密码输入完成
					if (this.paymentPassword.length === 6) {
						setTimeout(() => {
							this.processPayment()
						}, 300)
					}
				}
			},

			// 处理支付
			processPayment() {
				uni.showLoading({
					title: '支付中...'
				})

				this.$api.point.PayPointOrders({
					pay_order_id: this.pay_order_id,
					good_desc: this.orderProducts[0].spu_name,
					paymentPassword: this.$secret.encryptAES(this.paymentPassword)
				}).then(res => {
					uni.hideLoading();
					// 余额支付成功
					this.passwordPopupShow = false
					this.paymentPassword = ''

					uni.showToast({
						title: res.msg,
						icon: 'success'
					})

					setTimeout(() => {
						if (this.selectedMethod === 1) {
							uni.redirectTo({
								url: `/points-package/order/success?amount=${this.finalPoints}`
							})
						} else {
							let cards = ''
							this.finalCards.forEach(item => {
								cards += item.count + item.level + ' '
							})
							cards = cards.trimEnd()
							uni.redirectTo({
								url: `/points-package/order/success?cards=${cards}`
							})
						}
					}, 1500)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.payment-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding: 20rpx;
		padding-bottom: calc(180rpx + env(safe-area-inset-bottom));
	}

	.amount-section {
		background-color: #ffffff;
		padding: 60rpx 40rpx;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.amount-header {
		margin-bottom: 30rpx;
	}

	.amount-label {
		font-size: 28rpx;
		color: #666;
	}

	.amount-display {
		display: flex;
		align-items: baseline;
		justify-content: center;
		margin-bottom: 20rpx;
	}

	.amount-symbol {
		font-size: 32rpx;
		color: #ff4757;
		margin-right: 8rpx;
	}

	.amount-value {
		font-size: 72rpx;
		font-weight: bold;
		color: #ff4757;
	}

	.amount-desc {
		font-size: 26rpx;
		color: #999;
	}

	/* 通用区块样式 */
	.product-section,
	.payment-methods,
	.cost-section,
	.delivery-section,
	.address-section {
		background: white;
		border-radius: 24rpx;
		padding: 40rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.section-title {
		margin-bottom: 30rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.add-address-btn {
		background: #1c705e;
		color: white;
		border: none;
		padding: 16rpx 32rpx;
		border-radius: 12rpx;
		font-size: 28rpx;
	}

	/* 商品信息样式 */
	.product-list {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
	}

	.product-item {
		display: flex;
		gap: 24rpx;
		padding: 24rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 16rpx;
	}

	.product-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 16rpx;
		flex-shrink: 0;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 8rpx;
	}

	.product-spec {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 16rpx;
	}

	.product-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.product-price {
		font-size: 32rpx;
		font-weight: 600;
		color: #e53935;
	}

	.product-quantity {
		font-size: 28rpx;
		color: #666;
	}

	/* 费用明细样式 */
	.cost-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 0;
	}

	.cost-item.total {
		border-top: 2rpx solid #e5e5e5;
		padding-top: 24rpx;
		margin-top: 16rpx;
		font-weight: 600;
		font-size: 32rpx;
	}

	.cost-label {
		color: #666;
		font-size: 28rpx;
	}

	.cost-value {
		color: #333;
		font-weight: 500;
		font-size: 28rpx;
	}

	.cost-item.total .cost-value {
		color: #e53935;
		font-size: 36rpx;
		font-weight: 600;
	}

	/* 配送方式样式 */
	.delivery-options {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.delivery-item {
		border: 4rpx solid #e5e5e5;
		border-radius: 24rpx;
		padding: 32rpx;
		cursor: pointer;
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		gap: 24rpx;
	}

	.delivery-item.active {
		border-color: #1c705e;
		background-color: #f0f8f5;
	}

	.delivery-info {
		flex: 1;
	}

	.delivery-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 8rpx;
	}

	.delivery-desc {
		font-size: 28rpx;
		color: #666;
	}

	.delivery-radio {
		margin-left: auto;
	}

	.radio {
		display: inline-block;
		width: 40rpx;
		height: 40rpx;
		border: 4rpx solid #ddd;
		border-radius: 50%;
		position: relative;
	}

	.radio.checked {
		border-color: #1c705e;
	}

	.radio.checked::after {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 20rpx;
		height: 20rpx;
		background-color: #1c705e;
		border-radius: 50%;
	}

	/* 地址列表样式 */
	.address-list {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.address-item {
		border: 4rpx solid #e5e5e5;
		border-radius: 24rpx;
		padding: 32rpx;
		cursor: pointer;
		transition: all 0.3s ease;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.address-item.active {
		border-color: #1c705e;
		background-color: #f0f8f5;
	}

	.address-content {
		flex: 1;
	}

	.address-header {
		display: flex;
		align-items: center;
		gap: 24rpx;
		margin-bottom: 16rpx;
	}

	.recipient-name {
		font-weight: 600;
		color: #333;
		font-size: 32rpx;
	}

	.recipient-phone {
		color: #666;
		font-size: 28rpx;
	}

	.default-tag {
		background-color: #1c705e;
		color: white;
		padding: 4rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
	}

	.address-detail {
		color: #666;
		font-size: 28rpx;
		line-height: 1.4;
	}

	.address-radio {
		margin-left: 24rpx;
	}

	.section-title {
		margin-bottom: 30rpx;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.method-list {
		margin-top: 20rpx;
	}

	.method-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.method-item:last-child {
		border-bottom: none;
	}

	.method-item.active {
		background-color: #f8fff8;
		border-radius: 12rpx;
		padding: 30rpx 20rpx;
		margin: 0 -20rpx;
	}

	.method-left {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.method-icon {
		width: 60rpx;
		height: 60rpx;
		margin-right: 20rpx;
	}

	.method-info {
		flex: 1;
	}

	.method-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.method-desc {
		font-size: 24rpx;
		color: #666;
		display: block;
	}

	.coupon-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		padding: 40rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.coupon-left {
		display: flex;
		align-items: center;
	}

	.coupon-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 16rpx;
	}

	.coupon-right {
		display: flex;
		align-items: center;
	}

	.coupon-selected {
		font-size: 28rpx;
		color: #ff4757;
		margin-right: 16rpx;
	}

	.coupon-placeholder {
		font-size: 28rpx;
		color: #999;
		margin-right: 16rpx;
	}

	/* 底部支付按钮 */
	.payment-footer {
		background: white;
		padding: 32rpx 40rpx;
		border-top: 2rpx solid #e5e5e5;
		display: flex;
		justify-content: space-between;
		align-items: center;
		z-index: 100;
	}

	.payment-info {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.total-label {
		font-size: 32rpx;
		color: #666;
	}

	.total-amount {
		font-size: 40rpx;
		font-weight: 600;
		color: #e53935;
	}

	.pay-btn {
		background-color: #1c705e;
		color: white;
		border: none;
		padding: 24rpx 64rpx;
		border-radius: 50rpx;
		font-size: 32rpx;
		font-weight: 500;
		transition: background-color 0.3s ease;
	}

	.pay-btn:disabled {
		background-color: #ccc;
	}

	/* 弹窗样式 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
	}

	.address-modal {
		background: white;
		border-radius: 24rpx;
		width: 90%;
		max-width: 1000rpx;
		max-height: 80vh;
		overflow-y: auto;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx;
		border-bottom: 2rpx solid #e5e5e5;
	}

	.modal-title {
		font-size: 36rpx;
		color: #333;
		font-weight: 600;
	}

	.close-btn {
		background: none;
		border: none;
		font-size: 48rpx;
		color: #666;
		padding: 0;
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.modal-content {
		padding: 40rpx;
	}

	.form-group {
		margin-bottom: 40rpx;
	}

	.form-label {
		display: block;
		margin-bottom: 16rpx;
		font-weight: 500;
		color: #333;
		font-size: 28rpx;
	}

	.form-input,
	.form-textarea {
		width: 100%;
		padding: 24rpx;
		border: 2rpx solid #ddd;
		border-radius: 12rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}

	.form-textarea {
		height: 160rpx;
		resize: vertical;
	}

	.checkbox-group {
		display: flex;
		align-items: center;
	}

	.checkbox-label {
		display: flex;
		align-items: center;
		gap: 16rpx;
		font-size: 28rpx;
		color: #333;
	}

	.modal-footer {
		display: flex;
		gap: 24rpx;
		padding: 40rpx;
		border-top: 2rpx solid #e5e5e5;
	}

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		padding: 24rpx;
		border: none;
		border-radius: 12rpx;
		font-size: 32rpx;
	}

	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;
	}

	.confirm-btn {
		background-color: #1c705e;
		color: white;
	}

	/* 兑换方式 */
	.exchange-methods {
		flex: 1;
		margin-right: 20rpx;
	}

	.method-item {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.method-item:last-child {
		margin-bottom: 0;
	}

	.method-label {
		font-size: 28rpx;
		color: #666;
		margin-right: 16rpx;
		min-width: 60rpx;
	}

	.points-text {
		font-size: 28rpx;
		font-weight: bold;
		color: #ff6b35;
	}

	.cards-requirement {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.card-req {
		font-size: 22rpx;
		font-weight: bold;
		padding: 2rpx 8rpx;
		border-radius: 8rpx;
		margin-right: 6rpx;
		margin-bottom: 4rpx;
		color: white;
	}

	.card-req.S {
		background-color: #ff6b35;
	}

	.card-req.A {
		background-color: #52a58a;
	}

	.card-req.B {
		background-color: #3498db;
	}

	.card-req.C {
		background-color: #9b59b6;
	}

	.card-req.D {
		background-color: #95a5a6;
	}

	.exchange-btn {
		background-color: #52a58a;
		color: white;
		padding: 12rpx 24rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
	}

	.exchange-btn.disabled {
		background-color: #ccc;
	}

	.btn-text {
		font-size: 24rpx;
	}

	/*支付密码框*/

	.password-popup {
		width: 600rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.popup-content {
		padding: 40rpx;
		text-align: center;
	}

	.popup-amount {
		font-size: 48rpx;
		font-weight: bold;
		color: #ff4757;
		margin-bottom: 40rpx;
	}

	.password-input {
		display: flex;
		justify-content: center;
		margin-bottom: 40rpx;
	}

	.password-dot {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 50%;
		margin: 0 10rpx;
	}

	.password-dot.filled {
		background-color: #333;
	}

	.number-keyboard {
		border-top: 2rpx solid #f5f5f5;
	}

	.keyboard-row {
		display: flex;
	}

	.keyboard-key {
		flex: 1;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-right: 2rpx solid #f5f5f5;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.keyboard-key:last-child {
		border-right: none;
	}

	.keyboard-row:last-child .keyboard-key {
		border-bottom: none;
	}

	.key-text {
		font-size: 36rpx;
		color: #333;
	}
</style>